package ar.com.android.restoapp.forms;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import ar.com.android.restoapp.forms.R;
import ar.com.android.restoapp.adapters.SpinnerTablesAdapter;
import ar.com.android.restoapp.dbHelpers.SQLFoodOrderHelper;
import ar.com.android.restoapp.entities.Order;
import ar.com.android.restoapp.entities.OrderItems;
import ar.com.android.restoapp.entities.Tables;
import ar.com.android.restoapp.http.CustomHttpClient;
import ar.com.android.restoapp.providers.OrderItemDataSource;
import ar.com.android.restoapp.providers.OrderProvider;
import ar.com.android.restoapp.providers.TablesProvider;
import ar.com.android.restoapp.utils.AppGlobalVariables;
import ar.com.android.restoapp.utils.Constants;
import ar.com.android.restoapp.utils.PrintUtils;
import ar.com.android.restoapp.utils.SyncDatabase;

public class MenuActivity extends Activity {
	
	//Defined Object Form and LogTag
	private static final String TAG = "MenuActivity";
	private static final int iActionOpenTable = 0;
	private static final int iActionSendOrder = 1;
	private static final int iActionCloseTable = 2;
	
	private static final int iTableOpened = 1;
	private static final int iTableBusy = 2;
	
	private static final int iTableCloseOK = 1;
	private static final int iTableCloseERR = 2;
	private static final int iTableNotBusy = 3;
	private static final int iTableClose = 4;

	//Enum for Menu Activity
	public enum MenuOptions {
		MENU_FOODS(1), MENU_GARRISONS(2), MENU_DRINKS(3), MENU_DESSERTS(4), MENU_EXIT(5);
		private int code;
		MenuOptions(Integer code) {this.code = code;}
		public static MenuOptions valueOf(int itemId) {
			for (MenuOptions menuOption : MenuOptions.values()) {
                if (itemId == menuOption.code) 
                    return menuOption;
            } 
			return null;
		}
	}
	
	TextView tvUserCompleteName;
	Spinner spiTables;
	EditText etQuantityGuest;
	EditText etTablesOpened;
	TextView tvTableState;
	
	ProgressDialog dialog;

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		
		setTitle(getString(R.string.app_name) + " - " + getString(R.string.mainTitle));
		
		SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(this);
		sqlHelper.dbOpen();
		
		try {
			TablesProvider tablesDataSource = new TablesProvider(this);
			
			//Populate UserCompleteName
			tvUserCompleteName = (TextView) findViewById(R.id.lblUserName);
			tvUserCompleteName.setText(AppGlobalVariables.getInstance().getUserCompleteName());
			
			//Get All Object in Form
			etTablesOpened = (EditText) findViewById(R.id.etTablesOpened);
			etQuantityGuest = (EditText) findViewById(R.id.etQuantityGuest);
			tvTableState = (TextView) findViewById(R.id.tvTableState);
			
			etTablesOpened.setEnabled(false);
						
			//Populate Tables on Spinner
			spiTables = (Spinner) findViewById(R.id.spiTables);
			
			List<Tables> lstTables = tablesDataSource.getAllTables();					
			
			SpinnerTablesAdapter adapter = new SpinnerTablesAdapter(this, android.R.layout.simple_spinner_dropdown_item, lstTables);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spiTables.setAdapter(adapter);
			
			etTablesOpened.setText(getTablesState(Constants.TABLE_BUSY).toString());
			
			//Set Listeners
			etQuantityGuest.setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if(!etQuantityGuest.getText().toString().equals("") && Integer.parseInt(etQuantityGuest.getText().toString())>0)
					{
						Tables table = (Tables)spiTables.getSelectedItem();
						table.setQuantityGuest(Integer.parseInt(etQuantityGuest.getText().toString()));
					}
					return false;
				}
			});
			
			spiTables.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
					try
					{
						Tables table = (Tables)spiTables.getSelectedItem();
						//Set Quantity Guest
						if(table.getQuantityGuest() == 0)
							etQuantityGuest.setText("");
						else
							etQuantityGuest.setText(table.getQuantityGuest().toString());
						
						//Search if state tale is close
						if(table.getState().equals(Constants.TABLE_CLOSE))
							SyncDatabase.syncDatabaseTableStatus(MenuActivity.this, table.getIdTable());
							
						//Set Table State
						if(table.getState().equals(Constants.TABLE_FREE))
							tvTableState.setText(getString(R.string.tableFree));
						else if(table.getState().equals(Constants.TABLE_BUSY))
							tvTableState.setText(getString(R.string.tableBusy));
						else if(table.getState().equals(Constants.TABLE_CLOSE))
							tvTableState.setText(getString(R.string.tableClose));
					}
					catch (Exception e) {
						Log.e(TAG, e.toString());
					}
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
				}
			});
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
		finally{
			sqlHelper.dbClose();
		}
	}
	
	@Override  
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			menu.add(0, MenuOptions.MENU_FOODS.code, 0, R.string.menuFoods).setIcon(R.drawable.ic_menu_food);
			menu.add(0, MenuOptions.MENU_GARRISONS.code, 0, R.string.menuGarrisons).setIcon(R.drawable.ic_menu_garrisons);
			menu.add(0, MenuOptions.MENU_DRINKS.code, 0, R.string.menuDrinks).setIcon(R.drawable.ic_menu_drinks);
			menu.add(0, MenuOptions.MENU_DESSERTS.code, 0, R.string.menuDesserts).setIcon(R.drawable.ic_menu_desserts);
			menu.add(0, MenuOptions.MENU_EXIT.code, 0, R.string.menuExitApp).setIcon(R.drawable.ic_menu_exit);
		    return super.onCreateOptionsMenu(menu);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		if(item.getItemId() == Constants.MENU_EXIT)
		{
			AlertDialog.Builder alertDialogExit = new AlertDialog.Builder(this);
			alertDialogExit.setMessage(getString(R.string.exitAppMsg))
				.setCancelable(false)       
				.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {           
						public void onClick(DialogInterface dialog, int id) {
							MenuActivity.this.finish();           
						}       
					})
				.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {           
						public void onClick(DialogInterface dialog, int id) {                
							dialog.cancel();           
						}      
					});
			alertDialogExit.create();
			alertDialogExit.show();
		}
		else
		{	
			Tables table = (Tables)spiTables.getSelectedItem();
			if(table.getState().equals(Constants.TABLE_BUSY))
			{
				if(etQuantityGuest.getText().toString().equals("")) {
					LayoutInflater inflater = getLayoutInflater();
					View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

					TextView text = (TextView) layout.findViewById(R.id.text);
					text.setText(getText(R.string.msgInputGuets));

					Toast toast = new Toast(getApplicationContext());
					toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
					toast.setDuration(Toast.LENGTH_LONG);
					toast.setView(layout);
					toast.show();
				}
				else
				{
					Intent intentOrder = new Intent(this, OrderActivity.class);
					intentOrder.putExtra("selectedTable", table.getIdTable());
					
					MenuOptions menuOptions = MenuOptions.valueOf(item.getItemId());
					Integer menuSelected = 0;
					
					switch (menuOptions) {
						case MENU_FOODS:
							menuSelected = Constants.MENU_FOODS;
							break;
						case MENU_GARRISONS:
							menuSelected = Constants.MENU_GARRISONS;
							break;
						case MENU_DRINKS:
							menuSelected = Constants.MENU_DRINKS;
							break;
						case MENU_DESSERTS:
							menuSelected = Constants.MENU_DESSERTS;
							break;
					default:
						break;
					}
					intentOrder.putExtra("selectedMenu", menuSelected);
					startActivityForResult(intentOrder, 1);
				}
			}
			else {
				LayoutInflater inflater = getLayoutInflater();
				View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

				TextView text = (TextView) layout.findViewById(R.id.text);
				text.setText(getText(R.string.msgTablesOpen));

				Toast toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				toast.setDuration(Toast.LENGTH_LONG);
				toast.setView(layout);
				toast.show();
			}
		}
		return true;
	}
	
	private Integer getTablesState(String state)
	{
		Integer iCount = 0;
		for(Tables table:((SpinnerTablesAdapter)spiTables.getAdapter()).items)
		{
			if(table.getState().equals(state))
				iCount++;
		}
		return iCount;
	}

    public void OnClickOpenMenu(View v) throws Exception
    {
        openOptionsMenu();
    }
		
	public void OnClickOpenTable(View v) throws Exception
	{
		dialog = ProgressDialog.show(this, "", getString(R.string.loadingOpeningTable));
		
		new Thread() {
			
			@Override
			public void run() {
				SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(MenuActivity.this);
				sqlHelper.dbOpen();
				
				sqlHelper.beginTransaction();
				
				try
				{
					//Check Table from WEB
					Tables table = SyncDatabase.syncDatabaseTableStatus(MenuActivity.this, ((Tables)spiTables.getSelectedItem()).getIdTable());
					if(table.getState().equals(Constants.TABLE_BUSY)) {
						Message msg = Message.obtain(); 
		                msg.what = iActionOpenTable; 
		                msg.obj = iTableBusy;
		                handler.sendMessage(msg);
					}
					else if(table.getState().equals(Constants.TABLE_CLOSE)) {
						Message msg = Message.obtain(); 
		                msg.what = iActionOpenTable; 
		                msg.obj = iTableClose;
		                handler.sendMessage(msg);
					}
					else
					{
						TablesProvider tablesDataSource = new TablesProvider(MenuActivity.this);
						table.setState(Constants.TABLE_BUSY);
						tablesDataSource.updateTable(table);
						
						((Tables)spiTables.getSelectedItem()).setState(Constants.TABLE_BUSY);
						
						OrderProvider orderDataSource = new OrderProvider(MenuActivity.this);
						orderDataSource.removeOrderTable(table.getIdTable());
						
						ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
						postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_SETTABLE_STATE));
						postParameters.add(new BasicNameValuePair(Constants.PARAM_TABLESTATE, table.getState()));
						postParameters.add(new BasicNameValuePair(Constants.PARAM_IDTABLE, table.getIdTable().toString()));
						
						CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
						
						Message msg = Message.obtain(); 
		                msg.what = iActionOpenTable; 
		                msg.obj = iTableOpened;
		                handler.sendMessage(msg);
					}
					sqlHelper.commitTransaction();
					sqlHelper.dbClose();
				}
				catch (Exception e) {
					Log.e(TAG, e.toString());
					sqlHelper.rollbackTransaction();
				}
				finally{
					sqlHelper.dbClose();
				}
				//Dismiss the progress dialog
				dialog.dismiss();
			}
		}.start();
	}
	
	public void OnClickConfirm(View v) throws Exception
	{
		dialog = ProgressDialog.show(this, "", getString(R.string.loadingSendingOrder));
		
		new Thread() {
	
			@Override
			public void run() {
		
				SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(MenuActivity.this);
				ArrayList<NameValuePair> postParameters;
				
				sqlHelper.dbOpen();
				sqlHelper.beginTransaction();
				
				try
				{			
					String ticketOrder = "";
					String ticketOrderItems = "";
					String ticketComment = "";
					
					OrderProvider orderDataSource = new OrderProvider(MenuActivity.this);
					OrderItemDataSource orderItemDataSource = new OrderItemDataSource(MenuActivity.this);
					
					TablesProvider tablesProvider = new TablesProvider(MenuActivity.this);
					Tables table = tablesProvider.getTable(((Tables)spiTables.getSelectedItem()).getIdTable());
					
					ticketOrder += table.getDescription() + "\n\n";
					
					//Make OrderHeader with data
					Order order = new Order();
					order.setIdTable(table.getIdTable());
					order.setNumGuest(Integer.parseInt(etQuantityGuest.getText().toString()));
					order.setState(Constants.TABLE_BUSY);
					order.setDateFrom(new Date());
					Long idOrderHeader = orderDataSource.insertOrder(order);
					
					SimpleDateFormat sdf = new SimpleDateFormat(Constants.FORMAT_ANDROID_DATETIME);
					
					//Send data to Server
					JSONObject joOrder = new JSONObject();
					
					joOrder.put("idTable", order.getIdTable());
					joOrder.put("numGuest", order.getNumGuest());
					joOrder.put("state", order.getState());
					joOrder.put("idRestaurant", AppGlobalVariables.getInstance().getIdRestaurant());
					joOrder.put("dateFrom", sdf.format(order.getDateFrom()));
								
					List<OrderItems> orderItems = orderItemDataSource.getAllOrderItems(table.getIdTable());
					
					JSONArray jaOrderItems = new JSONArray();
					for(OrderItems orderItem: orderItems)
					{
						if(orderItem.getState().equals(Constants.ORDER_ITEM_PENDING_SEND))					
							ticketOrderItems += orderItem.getOrderDescription().concat(Constants.blankSpaces).substring(0, 40) + '\t' + orderItem.getOrderQuantity() + '\n';
		
						JSONObject joItem = new JSONObject();
						joItem.put("idOrderHeader", idOrderHeader);
						joItem.put("idFood", orderItem.getIdFood());
						joItem.put("quantity", orderItem.getOrderQuantity());
						joItem.put("price", orderItem.getPrice());
						
						jaOrderItems.put(joItem);
						
						orderItem.setState(Constants.ORDER_ITEM_SUBMITTED);
						orderItemDataSource.updateOrderItem(orderItem);
						
					}
					
					ticketComment = "\n" + table.getComments();
		
					postParameters = new ArrayList<NameValuePair>();
					postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_SETORDER));
					postParameters.add(new BasicNameValuePair(Constants.PARAM_DATAORDER, "[" + joOrder.toString() + "]"));
					postParameters.add(new BasicNameValuePair(Constants.PARAM_DATAORDER_ITEM, jaOrderItems.toString()));
					postParameters.add(new BasicNameValuePair(Constants.PARAM_COMMENTS, table.getComments()));
					
					String response = CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
					JSONObject jsonResponse = new JSONObject(response);
					
					if(jsonResponse.getString("status").equals("OK"))
					{
						if(!PrintUtils.isSend2PrinterInstalled(MenuActivity.this)) {
							sqlHelper.commitTransaction();
							Message msg = Message.obtain(); 
			                msg.what = iActionSendOrder; 
			                msg.obj = getString(R.string.msgPrinterNotInstalled);
			                handler.sendMessage(msg);
			                
			                table.setComments("");
			                tablesProvider.updateTable(table);
						}
						else {
							if(ticketOrderItems.length()>0) {
								ticketOrder = ticketOrder + ticketOrderItems + ticketComment; 
								PrintUtils.queueTextForPrinting(MenuActivity.this, ticketOrder);
							}
							
			                table.setComments("");
			                tablesProvider.updateTable(table);
			                
							//Commit Transaction
							sqlHelper.commitTransaction();
							Message msg = Message.obtain(); 
			                msg.what = iActionSendOrder; 
			                msg.obj = getString(R.string.msgSendingComplete);
			                handler.sendMessage(msg);
						}
					}
					else
					{
						sqlHelper.rollbackTransaction();
						Message msg = Message.obtain(); 
		                msg.what = iActionSendOrder; 
		                msg.obj = getString(R.string.msgSendingCompleteError);
		                handler.sendMessage(msg);
					}
				}
				catch (Exception e) {
					Log.e(TAG, e.toString());
					sqlHelper.rollbackTransaction();
					Message msg = Message.obtain(); 
	                msg.what = iActionSendOrder; 
	                msg.obj = getString(R.string.msgSendingCompleteError);
	                handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
	public void OnClickClose(View v) throws Exception
	{
		dialog = ProgressDialog.show(this, "", getString(R.string.loadingClosingTable));
		
		new Thread() {
	
			@Override
			public void run() {
				SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(MenuActivity.this);
				sqlHelper.dbOpen();
				
				try
				{
					sqlHelper.beginTransaction();
					
					Tables table = (Tables)spiTables.getSelectedItem();
					if(table.getState().equals(Constants.TABLE_BUSY))
					{
						OrderProvider orderDataSource = new OrderProvider(MenuActivity.this);
						Order order = orderDataSource.getOrder(table.getIdTable(), table.getState());
						order.setState(Constants.TABLE_CLOSE);
						order.setDateTo(new Date());
						orderDataSource.updateOrder(order);
						
						TablesProvider tablesDataSource = new TablesProvider(MenuActivity.this);
						table.setState(Constants.TABLE_CLOSE);
						table.setQuantityGuest(0);
						tablesDataSource.updateTable(table);
						
						OrderItemDataSource orderItemDataSource = new OrderItemDataSource(MenuActivity.this);
						orderItemDataSource.removeTableOrderItem(table.getIdTable());
						
						SimpleDateFormat sdf = new SimpleDateFormat(Constants.FORMAT_ANDROID_DATETIME);
						
						ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
						postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_SETTABLE_STATE));
						postParameters.add(new BasicNameValuePair(Constants.PARAM_TABLESTATE, table.getState()));
						postParameters.add(new BasicNameValuePair(Constants.PARAM_IDTABLE, table.getIdTable().toString()));
						postParameters.add(new BasicNameValuePair(Constants.PARAM_DATEORDERCLOSE, sdf.format(new Date())));
						
						String response = CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
						JSONObject jsonResponse = new JSONObject(response);
						
						if(jsonResponse.getString("status").equals("OK"))
						{
							sqlHelper.commitTransaction();
							
							Message msg = Message.obtain(); 
			                msg.what = iActionCloseTable; 
			                msg.obj = iTableCloseOK;
			                handler.sendMessage(msg);
						}
						else {
							sqlHelper.rollbackTransaction();
							Message msg = Message.obtain(); 
			                msg.what = iActionCloseTable; 
			                msg.obj = iTableCloseOK;
			                handler.sendMessage(msg);
						}
					}
					else
					{
						Message msg = Message.obtain(); 
		                msg.what = iActionCloseTable; 
		                msg.obj = iTableNotBusy;
		                handler.sendMessage(msg);
					}
				}
				catch (Exception e) {
					Log.e(TAG, e.toString());
					sqlHelper.rollbackTransaction();
					Message msg = Message.obtain(); 
	                msg.what = iActionCloseTable; 
	                msg.obj = iTableCloseERR;
	                handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
	private void showMesaggeActivity(Message msg)
	{
		try
		{
			LayoutInflater inflater;
			View layout;
			TextView text;
			Toast toast;
			
			switch (msg.what) {
				case iActionOpenTable:
					if((Integer)msg.obj == iTableBusy) {
						inflater = getLayoutInflater();
						layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

						text = (TextView) layout.findViewById(R.id.text);
						text.setText(getText(R.string.msgTableBusy));

						toast = new Toast(getApplicationContext());
						toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
						toast.setDuration(Toast.LENGTH_LONG);
						toast.setView(layout);
						toast.show();
					}
					else if((Integer)msg.obj == iTableOpened) {
						//Set Table State
						etQuantityGuest.setText("");
						tvTableState.setText(getString(R.string.tableBusy));
						etTablesOpened.setText(getTablesState(Constants.TABLE_BUSY).toString());
					}
					else if((Integer)msg.obj == iTableClose) {
						inflater = getLayoutInflater();
						layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

						text = (TextView) layout.findViewById(R.id.text);
						text.setText(getText(R.string.msgTableClose));

						toast = new Toast(getApplicationContext());
						toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
						toast.setDuration(Toast.LENGTH_LONG);
						toast.setView(layout);
						toast.show();
					}
					break;
				
				case iActionSendOrder:
					inflater = getLayoutInflater();
					layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

					text = (TextView) layout.findViewById(R.id.text);
					text.setText(msg.obj.toString());

					toast = new Toast(getApplicationContext());
					toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
					toast.setDuration(Toast.LENGTH_LONG);
					toast.setView(layout);
					toast.show();
					break;
		
				case iActionCloseTable:
					if((Integer)msg.obj == iTableCloseOK) {
						//Set Table State
						etQuantityGuest.setText("");
						tvTableState.setText(getString(R.string.tableClose));
					}
					else if((Integer)msg.obj == iTableNotBusy) {
						inflater = getLayoutInflater();
						layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

						text = (TextView) layout.findViewById(R.id.text);
						text.setText(getText(R.string.msgTableNotBusy));

						toast = new Toast(getApplicationContext());
						toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
						toast.setDuration(Toast.LENGTH_LONG);
						toast.setView(layout);
						toast.show();
					}
					else if((Integer)msg.obj == iTableCloseERR) {
						inflater = getLayoutInflater();
						layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

						text = (TextView) layout.findViewById(R.id.text);
						text.setText(getText(R.string.msgCloseTableError));

						toast = new Toast(getApplicationContext());
						toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
						toast.setDuration(Toast.LENGTH_LONG);
						toast.setView(layout);
						toast.show();
					}
					break;
					
				default:
					break;
			}
		}
		catch (Exception e) {
			Log.e(TAG, e.toString());
		}
		finally {
			dialog.dismiss();
		}
	}
	
	private Handler handler = new Handler() {
	        @Override
	        public void handleMessage(Message msg) {
	        	showMesaggeActivity(msg);
	        }
	};
}